package com.jie.flink.cdc.util;

import com.jie.flink.cdc.doman.TestDomain;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * @author zhanggj
 * @date 2023/5/5 17:56
 * @desc
 */
public class ObjectUtils {


    /**
     * 判断对象字段是否全部为空
     *
     * @param object 要判断的对象
     * @return true: 对象的所有字段都为空；false: 对象的某个字段不为空
     */
    public static boolean isAllFieldsEmpty(Object object) {
        if (object == null) {
            return true;
        }

        Field[] fields = object.getClass().getDeclaredFields();

        Predicate<Object> fieldIsEmpty = fieldValue -> {
            if (fieldValue == null) {
                return true;
            }
            if (fieldValue instanceof String) {
                return ((String) fieldValue).isEmpty();
            }
            return false;
        };

        return Stream.of(fields)
                .map(field -> {
                    try {
                        field.setAccessible(true);
                        return Optional.ofNullable(field.get(object));
                    } catch (IllegalAccessException e) {
                        return Optional.<Object>empty();
                    }
                })
                .allMatch(optionalValue -> optionalValue.filter(fieldIsEmpty).isPresent());
    }
    /**
     * 判断对象字段是否全部为空
     *
     * @param object 要判断的对象
     * @return true: 对象的所有字段都为空；false: 对象的某个字段不为空
     */
    public static boolean allFieldsEmpty(Object object) throws IllegalAccessException {
        if (object == null) {
            return true;
        }

        for (Field field : object.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            Object fieldValue = field.get(object);
            if (!Objects.isNull(fieldValue)) {
                if (fieldValue instanceof String) {
                    if (!((String) fieldValue).isEmpty()) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }

        return true;
    }


    public static void main(String[] args) {
        TestDomain testDomain = new TestDomain();

    }
}
